package com.learn.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

import javax.servlet.http.HttpServletResponse;

/**
 * @author PC
 */
@Configuration
@Order(66)
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                // 配置对/actuator/的请求进行拦截
                .authorizeRequests()
                // 仅允许10.9网段及本地访问端点
                .antMatchers("/actuator/**").access("hasIpAddress('10.9.0.0/16') or hasIpAddress('127.0.0.1')")
                .and()
                // 配置一个自定义的访问拒绝处理器（可选，但推荐用于明确的403响应）
                .exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to access!"));
        return http.build();
    }
}

